import os
import numpy as np
import sys


class Initer:
    def __init__(self):
        self.output_path = None
        self.terminal = sys.stdout
        self.log = open(os.path.join(self.create_next_folder(), "log.txt"), "a")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

    def flush(self):
        self.log.flush()

    def create_next_folder(self):
        if not os.path.exists("./Output"):
            os.makedirs("./Output")
        folder_names = os.listdir("./Output")
        indices = [int(name) for name in folder_names if name.isdigit()]
        next_folder_index = np.max(indices) + 1 if indices else 1
        next_folder_name = "{:04d}".format(next_folder_index)
        next_folder_path = os.path.join("./Output", next_folder_name)
        os.makedirs(os.path.join(next_folder_path, "Img"))
        os.makedirs(os.path.join(next_folder_path, "Model_C"))
        os.makedirs(os.path.join(next_folder_path, "Model_E"))
        os.makedirs(os.path.join(next_folder_path, "Results"))
        self.output_path = next_folder_path
        return next_folder_path

